package org.rufolfheszele.andpixelbyandpixel;

import java.util.List;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;

public class Vehicle
{
	public Vehicle(Point position, Bitmap bitmap, int dotSize)
	{
		mPosition = position;
		mSpeed = new Point(0, 0);
		mBitmap = bitmap;
		mDotSize = dotSize;
	}
	
	public Point getPosition()
	{
		return mPosition;
	}
	
	public Point getSpeed()
	{
		return mSpeed;
	}
	
	List<Point> getValidNextPositions()
	{
		Point nextPosition = new Point(mPosition.x + mSpeed.x, mPosition.y + mSpeed.y);
		List<Point> result = Utils.getPointsAround(nextPosition, mDotSize);
		
		result.add(nextPosition);
		
		return result;
	}
	
	boolean move(Point nextPosition)
	{
		boolean isNextPositionValid = false;
        List<Point> validPositions = this.getValidNextPositions();

        for(int i = 0; i < validPositions.size(); i++)
        {
        	if(nextPosition.equals(validPositions.get(i)))
            {
                isNextPositionValid = true;
                break;
            }
        }
        if(false == isNextPositionValid)
            return false;
        // Erase the vehicle from, the earlier position
        this.draw(true);
        // Assign the new values
        mSpeed = new Point(nextPosition.x - mPosition.x, nextPosition.y - mPosition.y);
        mPosition = nextPosition;
        // Draw the vehicle to the new position
        this.draw(false);

        return true;
	}
	
	void draw(boolean erase)
	{
		List<Point> points = Utils.getPointsAround(mPosition, 1);
        Canvas canvas = new Canvas(mBitmap);
        Paint paint = new Paint();

        if(true == erase)
        	paint.setColor(Color.WHITE);
        else
        	paint.setColor(Color.BLACK);
        for(int i = 0; i < points.size(); i++)
        	canvas.drawPoint(points.get(i).x, points.get(i).y, paint);
	}
	
	private Point mPosition	= null;
	private Point mSpeed	= null;
	Bitmap mBitmap			= null;
	int mDotSize			= 0;
}
